// 认证工具库
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { cookies } from 'next/headers';

// JWT配置
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production';
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '86400'; // 24小时

// 用户类型定义
export interface User {
  id: number;
  username: string;
  email?: string;
  display_name: string;
  avatar_url?: string;
  role: 'student' | 'teacher' | 'admin';
  created_at: Date;
  last_login_at?: Date;
}

// JWT载荷类型
export interface JWTPayload {
  userId: number;
  username: string;
  role: string;
  iat?: number;
  exp?: number;
}

// 密码加密
export async function hashPassword(password: string): Promise<string> {
  const salt = await bcrypt.genSalt(10);
  return await bcrypt.hash(password, salt);
}

// 密码验证
export async function verifyPassword(password: string, hash: string): Promise<boolean> {
  return await bcrypt.compare(password, hash);
}

// 生成JWT Token
export function generateToken(user: User): string {
  const payload: JWTPayload = {
    userId: user.id,
    username: user.username,
    role: user.role,
  };

  return jwt.sign(payload, JWT_SECRET, {
    expiresIn: parseInt(JWT_EXPIRES_IN),
  });
}

// 验证JWT Token
export function verifyToken(token: string): JWTPayload | null {
  try {
    return jwt.verify(token, JWT_SECRET) as JWTPayload;
  } catch (error) {
    return null;
  }
}

// 从Cookie获取Token
export function getTokenFromCookies(): string | null {
  try {
    const cookieStore = cookies();
    // 统一使用 'token' 作为cookie名称
    const token = cookieStore.get('token');
    return token?.value || null;
  } catch (error) {
    return null;
  }
}

// 从请求头获取Token
export function getTokenFromHeader(authHeader?: string): string | null {
  if (!authHeader) return null;
  
  // 支持 "Bearer token" 格式
  if (authHeader.startsWith('Bearer ')) {
    return authHeader.substring(7);
  }
  
  return authHeader;
}

// 获取当前用户（从Token）
export function getCurrentUser(token?: string): JWTPayload | null {
  const authToken = token || getTokenFromCookies();
  if (!authToken) return null;
  
  return verifyToken(authToken);
}

// 设置认证Cookie
export function setAuthCookie(token: string) {
  const cookieStore = cookies();
  // 统一使用 'token' 作为cookie名称
  cookieStore.set('token', token, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
    maxAge: parseInt(JWT_EXPIRES_IN),
    path: '/',
  });
}

// 清除认证Cookie
export function clearAuthCookie() {
  const cookieStore = cookies();
  // 统一使用 'token' 作为cookie名称
  cookieStore.delete('token');
}

// 验证用户名格式
export function validateUsername(username: string): { valid: boolean; error?: string } {
  if (!username || username.length < 3) {
    return { valid: false, error: '用户名至少3个字符' };
  }
  
  if (username.length > 20) {
    return { valid: false, error: '用户名最多20个字符' };
  }
  
  // 只允许字母、数字、下划线
  if (!/^[a-zA-Z0-9_]+$/.test(username)) {
    return { valid: false, error: '用户名只能包含字母、数字和下划线' };
  }
  
  return { valid: true };
}

// 验证密码格式
export function validatePassword(password: string): { valid: boolean; error?: string } {
  if (!password || password.length < 6) {
    return { valid: false, error: '密码至少6个字符' };
  }
  
  if (password.length > 50) {
    return { valid: false, error: '密码最多50个字符' };
  }
  
  return { valid: true };
}

// 验证邮箱格式
export function validateEmail(email: string): { valid: boolean; error?: string } {
  if (!email) {
    return { valid: true }; // 邮箱可选
  }
  
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(email)) {
    return { valid: false, error: '邮箱格式不正确' };
  }
  
  return { valid: true };
}

// API响应工具
export class ApiResponse {
  static success<T>(data: T, message?: string) {
    return Response.json({
      success: true,
      data,
      message,
    });
  }

  static error(message: string, status: number = 400) {
    return Response.json({
      success: false,
      error: message,
    }, { status });
  }

  static unauthorized(message: string = '未授权访问') {
    return Response.json({
      success: false,
      error: message,
    }, { status: 401 });
  }

  static forbidden(message: string = '无权限访问') {
    return Response.json({
      success: false,
      error: message,
    }, { status: 403 });
  }

  static notFound(message: string = '资源不存在') {
    return Response.json({
      success: false,
      error: message,
    }, { status: 404 });
  }

  static serverError(message: string = '服务器错误') {
    return Response.json({
      success: false,
      error: message,
    }, { status: 500 });
  }
}

export default {
  hashPassword,
  verifyPassword,
  generateToken,
  verifyToken,
  getTokenFromCookies,
  getTokenFromHeader,
  getCurrentUser,
  setAuthCookie,
  clearAuthCookie,
  validateUsername,
  validatePassword,
  validateEmail,
  ApiResponse,
};
